//
//  HMUserAccountViewModel.swift
//  sinaweibo
//
//  Created by WGP on 16/4/11.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

//专门处理HMuserAccount 模型的的相关操作,网络请求呀,字典喜欢模型,归档和解档
class HMUserAccountViewModel: NSObject {
    
//    单例
    static let sharedInstance = HMUserAccountViewModel()
    
    
//    把构造方法变成私有,在类外就不能再随便init一个对象
    private override init() {
        super.init()
        
//        加载账号
        userAccount = loadUserAccount()
    }
    
//    账号模型
    var userAccount: HMUserAccount?
    
//    用户是否登陆
    var userLogin: Bool
    {
        get
        {
            return userAccount != nil
        }
    }
    
    //    MARK: - 获取AccessToken的方法
    func loadAccessToken(code: String, loadAccessTokenCallBack:(error: NSError?)->())
    {
        //        1.urlString
        let urlStr = access_tokenURL
        
        //access_token请求参数,client_id,client_secret,grant_type,grant_type为authorization_code时,code,redirect_uri
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":grant_type,
            "code":code,
            "redirect_uri":redirect_uri,
        ]
        
        HMNetWorkTool.sharedInstance.POST(urlStr, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            
            
            let result = responseObject as? [String: AnyObject]
            
            if let dict = result
            {
                //字典转模型,并赋值给属性
                self.userAccount = HMUserAccount(dict: dict)

                
//              闭包里方法和属性要用self
                self.saveUserAccount()
                
                
//              获得保存账号后通知控制器已完成
                loadAccessTokenCallBack(error: nil)
            }
            
            }) { (task, error) -> Void in

//                失败回掉
                loadAccessTokenCallBack(error: error)
        }
    }
    
//    保存账号模型
    private func saveUserAccount()
    {
//          HMPrint("accountPath: \(accountPath)")
        if let userAccount = self.userAccount
        {
            //      归档
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        }
    }
    
    
     ///从沙盒里面接档UserAccount对象

    func loadUserAccount() ->HMUserAccount?
    {
//        接档账号,有可能有,也有可能没有
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HMUserAccount
        
//        可选绑定,判断账号是否有值,账号有值,判断是否过期
        if let account = userAccount where account.expiresDate?.compare(NSDate()) ==  NSComparisonResult.OrderedDescending
        {
                return account

        }
        return nil
    }
    
//    MARK: - 获取用户信息
    func loadUserInfo(loadUserInfoFinished:(error: NSError?)->())
    {
//        守卫,没有值就执行括号里的代码
        guard let _ = userAccount?.access_token else
        {
            HMPrint("access_token没有值")
            return
        }
        guard let uid = userAccount?.uid else
        {
            HMPrint("没有uid")
            return
        }
//        https://api.weibo.com/2/users/show.json?access_token=
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let parameters = [
            "access_token":userAccount!.access_token!,
            "uid":uid
        ]
        
        HMNetWorkTool.sharedInstance.GET(urlStr, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            

//            成功回调
            if let dict = responseObject as? [String: AnyObject]
            {

                
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                
//                将当前对象保存到沙盒里
                
                self.saveUserAccount()
                
                loadUserInfoFinished(error: nil)
            }
            
           
            
            }) { (_, error) -> Void in
                
//                失败回掉
            loadUserInfoFinished(error: error)
        }
    }
}









